package com.my.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.Student;
import com.my.entity.User;
import com.my.service.StudentService;
import com.my.service.TokenService;
import com.my.service.UserService;
import com.my.util.Rest;
import com.my.vo.Login;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@CrossOrigin
public class LoginController {

    @Resource
    private UserService uService;

    @Resource
    private StudentService sService;

    @Resource
    private TokenService tService;

    @PostMapping("login")
    public Rest login(@RequestBody Login login) {
        if(login.getType() != 3) {
            User user = uService.getOne(new QueryWrapper<User>().eq("username", login.getUsername()).eq("type", login.getType()));
            return getRest(login, user == null, user != null && user.isStatus(), user != null ? user.getPassword() : "", user != null ? user.getId() : -1L, user != null ? user.getType() : -1);
        } else {
            Student student = sService.getOne(new QueryWrapper<Student>().eq("username", login.getUsername()));
            return getRest(login, student == null, student != null && student.isStatus(), student != null ? student.getPassword() : "", student != null ? student.getId() : -1, 3);
        }
    }

    @PostMapping("logout")
    public Rest logout(@RequestHeader("authentication-token") String to) {
        if(tService.removeById(to)) {
            return Rest.ok("您已安全退出！");
        }
        return Rest.err("退出失败！");
    }

    private Rest getRest(@RequestBody Login login, boolean b, boolean status, String password, Long userId, Integer type) {
        if(b) {
            return Rest.err("当前用户不存在！");
        }
        if(!status) {
            return Rest.err("当前用户未启用！");
        }
        if(SecureUtil.md5(login.getPassword()).equals(password)) {
            String token = StrUtil.uuid();
            tService.createToken(token, userId, type);
            return Rest.ok("登录成功！").setData("token", token);
        }
        return Rest.err("用户名或密码错误");
    }

}
